'''
基础层：封装元素定位和操作；
'''
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from time import sleep
import logging

logging.basicConfig(level=logging.WARNING, format='%(asctime)s %(levelname)s %(name)s %(message)s')


class BasePage():
    base_url = r'http://172.16.22.111:8080'

    url = r'/bsams/front/login.do'

    def __init__(self, driver):
        self.driver = driver

    def _open(self, url):
        """实现：打开 url 页面 """
        full_url = self.base_url + url
        self.driver.get(full_url)
        self.driver.maximize_window()

    def open(self):
        """实现：打开 不同的 url 页面 """
        self._open(self.url)

    def find_ele(self, loc):
        """实现：元素定位"""
        ele = self.driver.find_element(*loc)
        return ele
        logging.info(f'定位{loc}成功')

    def input_ele(self, loc, value):
        """实现：输入框输入数据"""
        ele = self.find_ele(loc)
        ele.send_keys(value)
        logging.info(f'在{loc}输入{value}成功')

    def ele_click(self, loc):
        """实现：按钮点击"""
        ele = self.find_ele(loc)
        ele.click()
        logging.info(f'点击{loc}成功')

    def ele_clear(self, loc):
        """实现：输入框清空"""
        ele = self.find_ele(loc)
        ele.clear()
        logging.info(f'在{loc}清除文本成功')

    def ele_select(self, loc, value):
        ele = self.find_ele(loc)
        Select(ele).select_by_visible_text(value)
        logging.info(f'定位{loc}成功，选择{value}成功')

    def get_alert_text(self):
        text = self.driver.swich_to.alert.text
        return text

    def alert_click(self):
        self.driver.swich_to.alert.accept()


# 测试代码
if __name__ == '__main__':
    taksid_loc = (By.ID, 'taskId')
    username_loc = (By.ID, 'loginName')
    password_loc = (By.ID, 'password')
    vericode_loc = (By.ID, 'vericode')
    login_btn_loc = (By.XPATH, '//*[@id="fmedit"]/div[2]/div[6]/input')
    taskid = 1
    username = 'student'
    password = '123456'
    vericode = 'shtd'

    chrome_location = r'D:\RJCS\谷歌浏览器内网通紫域和驱动安装\chrome-win\chrome.exe'
    options = webdriver.ChromeOptions()
    options.binary_location = chrome_location

    driver = webdriver.Chrome(options=options)

    base_page = BasePage(driver)

    base_page.open()
    base_page.input_ele(taksid_loc, taskid)
    base_page.input_ele(username_loc, username)
    base_page.input_ele(password_loc, password)
    base_page.input_ele(vericode_loc, vericode)
    base_page.ele_click(login_btn_loc)
    sleep(3)

    driver.quit()
